package cn.otrue.patienthealthmanager.http;

import java.io.File;

import android.os.StrictMode;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseStream;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

/**
 * 
 * @author G
 * 
 */
public class HttpAsyncUtil {

	static HttpUtils http = new HttpUtils();
	static {
		// 设置缓存大小
		http.configHttpCacheSize(10000);
		// 设置线程池大小
		http.configRequestThreadPoolSize(100);
		// 重复次数
		http.configRequestRetryCount(3);

	}

	/**
	 * 异步get方法
	 * 
	 * @param urlString
	 *            请求参数
	 * @param callBack
	 *            回调类
	 */
	public static void get(String urlString, RequestCallBack<String> callBack) {

		http.send(HttpRequest.HttpMethod.GET, urlString, callBack);
	}

	/**
	 * 异步post方法
	 * 
	 * @param urlString
	 *            地址
	 * @param params
	 *            请求参数
	 * @param callBack
	 *            回调类
	 */
	public static void post(String urlString, RequestParams params,
			RequestCallBack<String> callBack) {

		http.send(HttpRequest.HttpMethod.POST, urlString, params, callBack);
	}

	/**
	 * 异步上传文件
	 * 
	 * @param urlString
	 *            地址
	 * @param file
	 *            上传的文件
	 * @param params
	 *            请求参数
	 * @param callBack
	 *            回调类
	 */
	public static void putFile(String urlString, File file,
			RequestParams params, RequestCallBack<String> callBack) {
		http.send(HttpRequest.HttpMethod.POST, urlString, params, callBack);

	}

	/**
	 * 异步下载文件
	 * 
	 * @param urlString
	 *            地址
	 * @param file
	 *            文件下载到F的路径
	 * @param params
	 *            请求参数
	 * @param callBack
	 *            回调类
	 */
	public static void getFile(String urlString, String filePath,
			RequestParams params, RequestCallBack<File> callBack) {
		http.download(urlString, filePath, params, true, true, callBack);
	}

	/**
	 * 同步Get方法
	 * 
	 * @param urlString
	 *            地址
	 * @param params
	 *            参数
	 * @return ResponseStream流对象
	 * @throws HttpException
	 * 
	 */
	public static ResponseStream getSync(String urlString, RequestParams params)
			throws HttpException {
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
				.detectDiskReads().detectDiskWrites().detectNetwork()
				.penaltyLog().build());
		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
				.detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath()
				.build());

		return http.sendSync(HttpRequest.HttpMethod.GET, urlString, params);

	}

	/**
	 * 拼接地址
	 * 
	 * @param action
	 * @return 拼接后的地址
	 */
	public static String getUrl(String action) {

		return HttpCons.URL + action;
	}

}
